package com.example.springMVC.controller;

import com.example.springMVC.commons.Result;
import com.example.springMVC.commons.ServiceException;
import com.example.springMVC.commons.ServiceExceptionHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class FileController {


    @ResponseBody
    @RequestMapping("upload")
    public Result upload(MultipartFile file) throws IOException, ServiceException {
        //获取文件名称  a.jpg
        String fileName = file.getOriginalFilename();
        //文件存放路径
        String realPath = "C://Users//34321//GitHub//springMVC//upload//";
        File f1 = new File(realPath);
        if (!f1.exists()){
            boolean b = f1.mkdir();
            if (!b){
                throw new ServiceException("创建文件失败");
            }
        }
        //防止文件名重复 修改文件名
        String uuidName = UUID.randomUUID().toString();
        String newFile = uuidName + fileName.substring(fileName.lastIndexOf("."));
        File f = new File(realPath + newFile);
        file.transferTo(f);
        return Result.success(newFile);
    }
}
